import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_vant_kit/widgets/loading.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:upplate/DioUtil.dart';
import 'package:upplate/upplatecode.dart';

import 'util/SPUtil.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '车辆备案登记',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: [
        //此处
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        //此处
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
      home: MyHomePage(title: '车辆备案登记'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isLogining = false;

  void initUserInfo() async {
    bool success = await SpUtil.getInstance();
    if (success) {
      String username = SpUtil.preferences.getString("username");
      String password = SpUtil.preferences.getString("password");
      if (username != null && username != '') {
        _userNameCtrl.text = username;
      }
      if (password != null && password != '') {
        _passwordCtrl.text = password;
      }
      print(SpUtil.packageInfo.buildNumber);
      _updateUrl2 = "http://admin.inssuper.com/super-server/common/uplateAppUpdate/"+SpUtil.packageInfo.buildNumber;
      initXUpdate();
    }
    print("init-" + success.toString());
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initUserInfo();
  }

  String _updateUrl2="";

  ///强制更新
  void checkUpdateForce() {
    FlutterXUpdate.checkUpdate(url: _updateUrl2);
  }

  ///初始化
  void initXUpdate() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(
        ///是否输出日志
        debug: true,
        ///是否使用post请求
        isPost: false,
        ///post请求是否是上传json
        isPostJson: false,
        ///是否开启自动模式
        isWifiOnly: false,
        ///是否开启自动模式
        isAutoMode: false,
        ///需要设置的公共参数
        supportSilentInstall: false,
        ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
        enableRetry: false).then((value) {
        checkUpdateForce();
      })
          .catchError((error) {
        print(error);
      });
    } else {
      Toast.show("ios暂不支持XUpdate更新",context,duration: 3);
    }
  }

  void startLogin() {
    setState(() {
      _isLogining = true;
    });
  }

  void endLogin() {
    setState(() {
      _isLogining = false;
    });
  }

  saveStore(String key, String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(key, value);
  }

  final _formKey = GlobalKey<FormState>();
  TextEditingController _userNameCtrl = TextEditingController();
  TextEditingController _passwordCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.title),
      ),
      body: Center(
          child: Form(
        key: _formKey,
        child: Padding(
          padding: const EdgeInsets.all(50.0),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.center, children: <
                  Widget>[
            SizedBox(
              height: 80,
            ),
            TextFormField(
              controller: _userNameCtrl,
              decoration: const InputDecoration(
                  hintText: '请输入登录账户名',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.person),
                  contentPadding: const EdgeInsets.symmetric(
                      vertical: 4.0, horizontal: 10.0)),
              validator: (value) {
                if (value.isEmpty) {
                  return '请输入登录账户名';
                }
                return null;
              },
            ),
            SizedBox(
              height: 30,
            ),
            TextFormField(
              controller: _passwordCtrl,
              obscureText: true,
              decoration: const InputDecoration(
                  hintText: '请输入登录密码',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.lock),
                  contentPadding: const EdgeInsets.symmetric(
                      vertical: 4.0, horizontal: 10.0)),
              validator: (value) {
                if (value.isEmpty) {
                  return '请输入登录密码';
                }
                return null;
              },
            ),
            SizedBox(
              height: 50,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: CupertinoButton(
                    onPressed: () {
                      if (_formKey.currentState.validate()) {
                        showDialog(
                            context: context,
                            barrierDismissible: true,
                            builder: (context) {
                              return Center(
                                child: Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(4.0),
                                      color: Colors.white),
                                  padding: EdgeInsets.all(20),
                                  child: Loading(
                                    color: Colors.blueAccent,
                                    text: "正在登录...",
                                  ),
                                ),
                              );
                            });
                        DioUtil.postHttp("sysMng/login", params: {
                          "username": _userNameCtrl.text,
                          "password": _passwordCtrl.text,
                          "type": 2
                        }, onSuccess: (res) {
                          Map<String, dynamic> data = jsonDecode(res);
                          int code = data['code'];
                          Navigator.pop(context, 0);
                          if (code == 0) {
                            int userId = data['data']['mng']['id'];
                            String consumerSysCode =
                                data['data']['mng']['consumerSysCode'];
                            saveStore("userId", userId.toString());
                            saveStore("consumerSysCode", consumerSysCode);
                            Toast.show('欢迎您，' + data['data']['mng']['realname'],
                                context,
                                duration: 3);
                            saveStore("username", _userNameCtrl.text);
                            saveStore("password", _passwordCtrl.text);
                            Navigator.of(context).push(new CupertinoPageRoute(
                                builder: (BuildContext context) => Upplatecode(
                                      title: "填写备案登记信息",
                                    )));
                          }
                        }, buildContext: context);
                      }
                    },
                    child: Text(_isLogining ? "正在登录..." : "登录"),
                    color: Colors.blueAccent,
                  ),
                )
              ],
            )
          ]),
        ),
      )),
    );
  }
}
